package com.dhj.yygh.mongo_operation;

import com.dhj.yygh.model.hosp.Department;
import com.mongodb.client.result.DeleteResult;
import org.apache.catalina.LifecycleState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class DepartmentTemplate {
    @Autowired
    MongoTemplate template;

    // 通过 depcode 和 hoscode 查询科室信息
    public Department getDepartmentByDepcodeAndHoscode(String depcode, String hoscode) {
        Query query = new Query(Criteria.where("depcode").is(depcode).and("hoscode").is(hoscode));
        return template.findOne(query, Department.class);
    }

    // 按照 hoscode 和 depcode 查询删除科室信息
    public Long removeDepartmentByDepcodeAndHoscode(String hoscode, String depcode) {
        Query query = new Query(Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode));

        Department department = template.findOne(query, Department.class);

        if (department == null) {
            return 0L;
        }

        String id = department.getId();

        Query queryById = new Query(Criteria.where("_id").is(id));

        DeleteResult remove = template.remove(queryById, Department.class);

        return remove.getDeletedCount();
    }

    // 根据医院编号查询所有的科室信息
    public List<Department> getDepartmentListByHoscode(String hoscode) {
        Query query = new Query(Criteria.where("hoscode").is(hoscode));

        return template.find(query, Department.class);
    }
}
